package com.futures.investm.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.widget.Toast;

import com.futures.investm.Config;
import com.futures.investm.R;

import java.io.File;
import java.util.List;

/**
 * Author: ChenPengBo
 * Date: 2018/10/23
 * Desc: 图片工具类
 */
public class PhotoUtils {

    public static boolean isCameraUseAble(Context context) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }

    private static Intent getToCameraIntent(Context context, File outputFile) {
        if (!isCameraUseAble(context)) {
            Toast.makeText(context, R.string.cube_photo_no_camera, Toast.LENGTH_LONG).show();
            return null;
        }

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfoList == null && resolveInfoList.size() == 0) {
            Toast.makeText(context, R.string.cube_photo_can_not_use_camera, Toast.LENGTH_LONG).show();
            return null;
        }
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imageUri = FileProvider.getUriForFile(context, Config.PHOTO_AUTHORITY, outputFile);
        } else {
            imageUri = Uri.fromFile(outputFile);
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        return intent;
    }

    public static void toCamera(Activity activity, File outputFile, int requestCode) {
        Intent intent = getToCameraIntent(activity, outputFile);
        if (intent == null) return;
        activity.startActivityForResult(intent, requestCode);
    }

    public static void toCamera(Fragment fragment, File outputFile, int requestCode) {
        Intent intent = getToCameraIntent(fragment.getContext(), outputFile);
        if (intent == null) return;
        fragment.startActivityForResult(intent, requestCode);
    }

    private static Intent getToAlbumIntent(Context context) {
        try {
//            Intent intent = new Intent();
//            intent.setType("image/*");
//            intent.setAction(Intent.ACTION_GET_CONTENT);
//            activity.startActivityForResult(intent, requestCode);
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            // 如果限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            return intent;
        } catch (Exception e) {
            Toast toast = Toast.makeText(context, R.string.cube_photo_can_not_open_album, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
        return null;
    }

    public static void toAlbum(Activity activity, int requestCode) {
        Intent intent = getToAlbumIntent(activity);
        if (intent == null) return;
        activity.startActivityForResult(intent, requestCode);
    }

    public static void toAlbum(Fragment fragment, int requestCode) {
        Intent intent = getToAlbumIntent(fragment.getContext());
        if (intent == null) return;
        fragment.startActivityForResult(intent, requestCode);
    }

    private static Intent getToCropIntent(Context context, File file, File outputFile, int size) {
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }

        Uri imageUri;
        Uri outputUri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imageUri = FileProvider.getUriForFile(context, Config.PHOTO_AUTHORITY, file);
            outputUri = Uri.fromFile(outputFile);
        } else {
            imageUri = Uri.fromFile(file);
            outputUri = Uri.fromFile(outputFile);
        }
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        //设置宽高比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //设置裁剪图片宽高
        intent.putExtra("outputX", size > 0 ? size : 600);
        intent.putExtra("outputY", size > 0 ? size : 600);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        return intent;
    }

    public static void toCrop(Activity activity, File file, File outputFile, int size, int requestCode) {
        Intent intent = getToCropIntent(activity, file, outputFile, size);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void toCrop(Fragment fragment, File file, File outputFile, int size, int requestCode) {
        Intent intent = getToCropIntent(fragment.getContext(), file, outputFile, size);
        fragment.startActivityForResult(intent, requestCode);
    }

    @SuppressLint("NewApi")
    public static String uriToPath(Context context, Uri uri) {
        if (null == uri) {
            return null;
        }
        String urlStr = uri.toString();
        if (urlStr.startsWith("file://")) {
            return uri.getPath();
        }
        Cursor cursor = null;
        String idWhere;
        String id;
        String[] columns = {MediaStore.Images.Media.DATA};
        try {
            //4.4
            if (Build.VERSION.SDK_INT == 19 && DocumentsContract.isDocumentUri(context, uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                id = split[1];
                idWhere = MediaStore.Images.Media._ID + "=?";
                cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, idWhere, new String[]{id}, null);
            } else {
                cursor = context.getContentResolver().query(uri, columns, null, null, null);
            }
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }
}
